package sparkrandom

import org.apache.log4j.Logger

import java.io.File
import scala.util.Random

import java.io.{FileOutputStream, OutputStreamWriter}


object RNG {
  private val logger = Logger.getLogger(getClass.getName)
  private val rep = 1000
  val filePath = "src/person.txt"

  def main(args: Array[String]): Unit = {
    val file = new File(filePath)
    if (file.exists()) {
      file.delete
    }
    file.createNewFile()
    for (i <- 0 until rep) {
      //val jsonString: String = write(person)
      val name = generateName()
      val age = generateAge()
      val institute = generateInstitute()
      val phone = generatePhone()
      val gender = generateGender()
      val writeString = name + "," + age.toString + "," + institute + "," + phone + "," + gender
      val osw: OutputStreamWriter = new OutputStreamWriter(
        new FileOutputStream(filePath, true), "UTF-8")
      osw.write(writeString)
      osw.write("\r\n")
      osw.flush()
      osw.close()
    }
  }

  def generateOne(lowerLimit: Int, upperLimit: Int): Int = {
    Random.between(lowerLimit, upperLimit + 1)
  }

  def generateName(): String = {
    val len: Int = Random.between(2, 15)
    val array: Array[Char] = new Array[Char](len)
    for (i <- 0 until len) {
      array(i) = generateOne(97, 122).toChar
    }
    logger.info("new name generated: " + array.mkString("").capitalize)
    array.mkString("").capitalize
  }

  def generatePhone(): String = {
    // set 5 prefixes of phones
    val prefixList: List[Array[Int]] = List(Array(133), Array(137), Array(158), Array(178), Array(126))
    val prefixLen: Int = prefixList.length - 1
    // prepare prefix
    val prefix: Array[Int] = prefixList(generateOne(0, prefixLen))
    // prepare add-ons
    val phone: Array[Int] = new Array[Int](8)
    for (i <- 0 until 8) {
      phone(i) = generateOne(0, 1)
    }
    (prefix ++ phone).mkString("")
  }

  def generateGender(): String = {
    generateOne(0, 1) match {
      case 0 => "M"
      case _ => "F"
    }
  }

  def generateAge(): Int = {
    generateOne(15, 60)
  }

  def generateInstitute(): String = {
    val institutes: Array[String] = Array("information technology",
      "chemistry industry", "pharmaceutical and medicine", "electrical engineering")
    val i = generateOne(0, institutes.length - 1)
    institutes(i)
  }
}

